//
//  BuglyManager.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/5/17.
//

import Foundation

#if canImport(Bugly)
import Bugly

let BuglyAppID = "30e54a73d7"

class BuglyManager : NSObject{
    
    static let shared = BuglyManager()
    
    /// 初始化SDK
    static func initSDK(){
        
        let config = BuglyConfig()
        //SDK Debug信息开关, 默认关闭
        config.debugMode = ISDEBUG
        //卡顿监控开关，默认关闭
        config.blockMonitorEnable = true
        //卡顿监控判断间隔，单位为秒
        config.blockMonitorTimeout = 1
        /**
         * 控制自定义日志上报，默认值为BuglyLogLevelSilent，即关闭日志记录功能。
         * 如果设置为BuglyLogLevelWarn，则在崩溃时会上报Warn、Error接口打印的日志
         */
        config.reportLogLevel = .warn
        //非正常退出事件记录开关，默认关闭
        config.unexpectedTerminatingDetectionEnable = true
        //设置代理
        config.delegate = self.shared
        //初始化SDK
        Bugly.start(withAppId: BuglyAppID,config: config)
        
        let appVersion = AppInfo.appVersion
        //更新应用版本
        Bugly.updateAppVersion(appVersion)
        
        self.initLog()
    }
    
    /// 设置用户ID作为标识
    /// - Parameter userId: 用户ID
    static func setUserId(_ userId:String){
        //设置用户标识
        Bugly.setUserIdentifier(userId)
    }
    
    /// 初始化打印
    static func initLog(){
        /**
         *    @brief  初始化日志模块
         *
         *    @param level 设置默认日志级别，默认BLYLogLevelSilent
         *
         *    @param printConsole 是否打印到控制台，默认NO
         */
        BuglyLog.initLogger(.warn, consolePrint: ISDEBUG)
    }
    
    /// 打印
    /// - Parameter string: ~
    static func log(_ string:String!){
        
        BuglyLog.level(.warn, logs: string)
    }
}
extension BuglyManager{
    
    static func report(name:String ,reason:String){
        
        let exception = NSException.init(name: NSExceptionName.init(rawValue: name), reason: reason)
        Bugly.report(exception)
    }
}
extension BuglyManager : BuglyDelegate{
    /**
     *  发生异常时回调
     *
     *  @param exception 异常信息
     *
     *  @return 返回需上报记录，随异常上报一起上报
     */
    func attachment(for exception: NSException?) -> String? {
        
        return ""
    }
    /**
     *  发生sigkill时回调
     *
     *  @param exception 异常信息
     *
     *  @return 返回需上报记录，随sigkill异常上报一起上报，返回值由app开发者决定
     */
    func attachmentForSigkill() -> String? {
        
        return ""
    }
    /**
     *  策略激活时回调
     *
     *  @param tacticInfo
     *
     *  @return app是否弹框展示
     */
    func h5Alert(forTactic tacticInfo: [AnyHashable : Any]) -> Bool {
        
        return ISDEBUG
    }
}
#endif
